package com.qqt.csr.order.service.statemachine.condition.impl;

import com.qqt.csr.common.exception.BizException;
import com.qqt.csr.common.exception.StatusCode;
import com.qqt.csr.common.utils.ServiceAssert;
import com.qqt.csr.order.entity.WorkOrder;
import com.qqt.csr.order.enums.WorkOrderEventEnum;
import com.qqt.csr.order.service.statemachine.condition.ISubCondition;
import com.qqt.csr.order.service.statemachine.context.WorkOrderContext;
import org.springframework.stereotype.Component;

@Component
public class AllocatedWorkOrderSubCondition implements ISubCondition {

    @Override
    public boolean matches(WorkOrderEventEnum event) {
        return WorkOrderEventEnum.ALLOCATED.equals(event);
    }

    @Override
    public boolean isSatisfied(WorkOrderContext context) {
        WorkOrder toOrder = context.getToOrder();
        WorkOrder fromOrder = context.getFromOrder();
        ServiceAssert.isTrue(context.getOperatorId().equals(fromOrder.getCreatorId()), StatusCode.Common.ILLEGAL.getCode(), "无权限操作");
        ServiceAssert.isTrue(fromOrder.isToClaim(), StatusCode.Common.ILLEGAL.getCode(), "工单非待认领状态，分配失败！");
        if (fromOrder.isAllocated()) {
            if (fromOrder.getDesigneeId().equals(toOrder.getDesigneeId())) {
                throw new BizException(StatusCode.Common.ILLEGAL.getCode(), "已分配当前工单，无需再次分配！");
            } else {
                throw new BizException(StatusCode.Common.ILLEGAL.getCode(), "工单已分配处理人，分配失败！");
            }
        }

        return true;
    }
}
